﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;

// 持续性的结算物
public class DuringCalcObject : MonoBehaviour
{
    // 球形检测半径
    private float _radius = 2; // 伤害半径
    private float _duringTime = 1; // 技能持续时间
    private float _hurtRate = 0.5f; // 伤害频率

    private Action<List<Creature>> _hitCallback; // 打击到敌人，回调

    private Creature _owner;

    private TimerMgr.Timer _timerRate; // 伤害频率计时器

    public void Init(Creature owner, float radius, float hitRate, float duringTime, Action<List<Creature>> hitCallback)
    {
        _owner = owner;
        _radius = radius;
        _duringTime = duringTime;
        _hurtRate = hitRate;
        _hitCallback = hitCallback;

        var timerDuring = TimerMgr.Instance.CreateTimer(_duringTime, 1, destroySelf);

        _timerRate = TimerMgr.Instance.CreateTimer(_hurtRate, -1, checkHit);

        timerDuring.Name = "during";
        _timerRate.Name = "rate";

        _timerRate.Start();
        timerDuring.Start();
    }

    private void destroySelf()
    {
        _timerRate.Stop();
        GameObject.Destroy(gameObject);
    }

    // 检测伤害目标
    private void checkHit()
    {
        var retList = Physics.CapsuleCastAll(Vector3.up * -10, Vector3.up * 10, _radius, Vector3.up, 0);

        List<Creature> hitList = new List<Creature>();
        foreach (var ret in retList)
        {
            var creature = ret.transform.GetComponent<Creature>();
            if (creature != null && creature.CanBeAttack(_owner))
            {
                hitList.Add(creature);
            }
        }

        if (_hitCallback != null)
        {
            _hitCallback(hitList);
        }
    }
}

